//
//  KENowhCPWebVCViewControllerQtAerd.m
//  豪门彩票
//
//  Created by Qiang on 2018/6/9.
//  Copyright © 2018年 施冬伟. All rights reserved.
//

#import "KENowhCPWebVCViewControllerQtAerd.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <WebKit/WebKit.h>
#define LZSCREEN_HEIGHT [[UIScreen mainScreen]bounds].size.height
#define LZSCREEN_WIDTH [[UIScreen mainScreen]bounds].size.width

@interface KENowhCPWebVCViewControllerQtAerd ()<WKUIDelegate,WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet UIView *toolBar;
@property (nonatomic, strong)WKWebView *webView;
@property (weak, nonatomic) IBOutlet UIButton *cacheButton;
@property (weak, nonatomic) IBOutlet UIButton *refreshButton;
@property (weak, nonatomic) IBOutlet UIButton *gobackButon;
@property (weak, nonatomic) IBOutlet UIButton *gofawordButton;
@property (weak, nonatomic) IBOutlet UIButton *homeButton;
@property (weak, nonatomic) IBOutlet UIImageView *homeImgV;
@property (weak, nonatomic) IBOutlet UIImageView *gobackImgV;
@property (weak, nonatomic) IBOutlet UIImageView *refreshImgV;
@property (weak, nonatomic) IBOutlet UIImageView *gofowrdImgV;

@end

@implementation KENowhCPWebVCViewControllerQtAerd

- (void)viewDidLoad {
    [super viewDidLoad];
    self.toolBar.layer.shadowOffset = CGSizeMake(-5, -5);
     self.toolBar.layer.shadowOpacity = 0.3;
    self.toolBar.layer.shadowColor = [UIColor blackColor].CGColor;
    
    [self setupWebView];
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
     [_webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionPrior context:nil];
    [self setFreshStatus];
    
}
- (void)setFreshStatus{
    if (self.webView.canGoBack) {
        self.gobackImgV.image = [UIImage imageNamed:@"后退"];
    }else{
     self.gobackImgV.image = [UIImage imageNamed:@"后退灰"];
    }
    if (self.webView.canGoForward) {
      self.gofowrdImgV.image = [UIImage imageNamed:@"前进"];
    }else{
self.gofowrdImgV.image = [UIImage imageNamed:@"前进灰"];
    }
    if (self.webView.isLoading) {
  self.refreshImgV.image = [UIImage imageNamed:@"刷新灰"];
    }else{
self.refreshImgV.image = [UIImage imageNamed:@"刷新"];
    }
    NSURL *url = [NSURL URLWithString:self.urlString];
    if ([self.webView.URL isEqual:url]) {
        self.homeImgV.image = [UIImage imageNamed:@"首页灰"];
    }else{
       self.homeImgV.image = [UIImage imageNamed:@"首页"];
    }
}
- (void)setupWebView {
    
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, LZSCREEN_WIDTH, LZSCREEN_HEIGHT-46-[UIApplication sharedApplication].statusBarFrame.size.height)];
    if (LZSCREEN_HEIGHT == 812) {
        self.webView.frame = CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, LZSCREEN_WIDTH, LZSCREEN_HEIGHT-46-[UIApplication sharedApplication].statusBarFrame.size.height-34);
    }
     self.webView.UIDelegate = self;
    [self.view addSubview: self.webView];

    self.webView.navigationDelegate = self;
    NSURL *url = [NSURL URLWithString:self.urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
   
}

- (IBAction)buttonClick:(id)sender {
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
        case 1:
        {
             NSURL *url = [NSURL URLWithString:self.urlString];
            if (![self.webView.URL isEqual:url]) {
               
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                [self.webView loadRequest:request];

            }
            
        }
            break;
        case 2:{
            if (self.webView.canGoBack) {
                [self.webView goBack];
            }
        }
            break;
        case 3:{
            if (self.webView.canGoForward) {
                [self.webView goForward];
            }
        }
            break;
        case 4:{
            if (!self.webView.isLoading) {
                [self.webView reload];
            }
        }
            break;
        case 5:{
            [self cleanCacheAndCookie];
        }
            break;
        default:
            break;
    }
    [self setFreshStatus];
}
- (void)cleanCacheAndCookie{
    
    //清除cookies
    
    NSHTTPCookie *cookie;
    
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (cookie in [storage cookies]){
        
        [storage deleteCookie:cookie];
        
    }
    
    //清除UIWebView的缓存
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSURLCache * cache = [NSURLCache sharedURLCache];
    
    [cache removeAllCachedResponses];
    
    [cache setDiskCapacity:0];
    
    [cache setMemoryCapacity:0];
    [SVProgressHUD showSuccessWithStatus:@"清除成功"];
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD showWithStatus:@"loading"];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [SVProgressHUD dismiss];
    [self setFreshStatus];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD dismiss];
    [self setFreshStatus];
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}




#pragma mark - WKUIDelegate

// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    if([[navigationAction.request.URL host] isEqualToString:@"itunes.apple.com"] &&[[UIApplication sharedApplication] openURL:navigationAction.request.URL]){
        
        [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else if([navigationAction.request.URL.scheme containsString:@"weixin"]){
        if([[UIApplication sharedApplication]canOpenURL:navigationAction.request.URL])
        {
            [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            
        }else{
            if (!navigationAction.targetFrame.isMainFrame) {
                [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
            }
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }else if([navigationAction.request.URL.scheme containsString:@"mqq"])
    {
        if([[UIApplication sharedApplication]canOpenURL:navigationAction.request.URL])
        {
            [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            
        }else{
            if (!navigationAction.targetFrame.isMainFrame) {
                [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
            }
            decisionHandler(WKNavigationActionPolicyAllow);
        }
        
    }else if ([navigationAction.request.URL.scheme containsString:@"wechat"]){
        if([[UIApplication sharedApplication]canOpenURL:navigationAction.request.URL])
        {
            [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            
        }else{
            if (!navigationAction.targetFrame.isMainFrame) {
                [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
            }
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }else if ([navigationAction.request.URL.scheme containsString:@"alipay"]){
        if([[UIApplication sharedApplication]canOpenURL:navigationAction.request.URL])
        {
            [[UIApplication sharedApplication]openURL:navigationAction.request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            
        }else{
            if (!navigationAction.targetFrame.isMainFrame) {
                [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
            }
            decisionHandler(WKNavigationActionPolicyAllow);
        }
        
    }else{
        if (!navigationAction.targetFrame.isMainFrame) {
            [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    
    
}

// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    completionHandler();
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        if (self.webView.estimatedProgress >= 1) {
            [SVProgressHUD dismiss];
        }
        
    }
    [self setFreshStatus];
}

- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
